<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MutationObserver Demo</title>
<style>
  #observed-element {
    padding: 20px;
    background-color: #f9f9f9;
    border: 1px solid #ccc;
  }
</style>
</head>
<body>

<div id="observed-element">
  <button id="add-btn">Add Child</button>
  <button id="change-btn">Change Attribute</button>
</div>

<script>
  // 获取被观察的元素
  const targetNode = document.getElementById('observed-element');

  // 配置观察选项
  const config = { attributes: true, childList: true, subtree: true };

  // 观察者回调函数
  const callback = function(mutationsList, observer) {
    for(const mutation of mutationsList) {
      if (mutation.type === 'childList') {
        console.log('A child node has been added or removed.');
      } else if (mutation.type === 'attributes') {
        console.log(`The ${mutation.attributeName} attribute was modified.`);
      }
    }
  };

  // 创建一个 MutationObserver 实例并传入回调函数
  const observer = new MutationObserver(callback);

  // 以上面的配置开始观察目标节点
  observer.observe(targetNode, config);

  // 添加按钮事件监听器来触发变化
  document.getElementById('add-btn').addEventListener('click', () => {
    const newElement = document.createElement('p');
    newElement.textContent = 'New paragraph';
    targetNode.appendChild(newElement);
  });

  document.getElementById('change-btn').addEventListener('click', () => {
    targetNode.setAttribute('data-custom-attribute', 'New value');
  });

</script>

</body>
</html>